package com.ruoyi.iot.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.iot.domain.Device;
import com.ruoyi.iot.domain.Product;
import com.ruoyi.iotcommon.constant.DeviceConstant;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.iot.mapper.CommandMapper;
import com.ruoyi.iot.domain.Command;
import com.ruoyi.iot.service.ICommandService;
import com.ruoyi.iot.service.IDeviceService;
import com.ruoyi.iot.service.IProductService;
import com.ruoyi.iotcommon.constant.RocketTopicConstant;
import com.ruoyi.iotcommon.domain.CommandPostMessage;

/**
 * 指令记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-19
 */
@Slf4j
@Service(value = "commandService")
public class CommandServiceImpl implements ICommandService {

    @Resource
    private CommandMapper commandMapper;
    @Resource
    private IDeviceService deviceService;
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private IProductService productService;

    /**
     * 查询指令记录
     * 
     * @param id 指令记录主键
     * @return 指令记录
     */
    @Override
    public Command selectCommandById(Long id)
    {
        return commandMapper.selectCommandById(id);
    }

    /**
     * 查询指令记录列表
     * 
     * @param command 指令记录
     * @return 指令记录
     */
    @Override
    public List<Command> selectCommandList(Command command)
    {
        return commandMapper.selectCommandList(command);
    }

    /**
     * 新增指令记录
     * 
     * @param command 指令记录
     * @return 结果
     */
    @Override
    public int insertCommand(Command command) {
        return commandMapper.insertCommand(command);
    }

    /**
     * 修改指令记录
     * 
     * @param command 指令记录
     * @return 结果
     */
    @Override
    public int updateCommand(Command command)
    {
        return commandMapper.updateCommand(command);
    }

    /**
     * 批量删除指令记录
     * 
     * @param ids 需要删除的指令记录主键
     * @return 结果
     */
    @Override
    public int deleteCommandByIds(Long[] ids)
    {
        return commandMapper.deleteCommandByIds(ids);
    }

    /**
     * 删除指令记录信息
     * 
     * @param id 指令记录主键
     * @return 结果
     */
    @Override
    public int deleteCommandById(Long id)
    {
        return commandMapper.deleteCommandById(id);
    }

    @Override
    public void sendCommand(String productKey, String channelKey, String deviceKey, String params,Long userId,String source) {
        // 也可以设置同一个设备两条命令间隔，不能小于5秒，不能太频繁点击

        Device device = deviceService.selectDeviceByKey(productKey,deviceKey);
        Product product = productService.selectProductByKey(productKey);
        if(userId == null){
            // 系统下发的指令，userId为0
            userId = 0L;
        }
     
        Command command = new Command();
        command.setProductKey(productKey);
        command.setChannelKey(channelKey);
        command.setDeviceKey(deviceKey);
        command.setParams(params);
        command.setPostTime(new Date());
        command.setSource(source);
        command.setUserId(userId);
        if(device == null){
            command.setCode(500);
            command.setMessage("设备不存在");
            insertCommand(command);
            return;
        }
        // 生成命令id，同一个设备永不重复
        String commandId = String.valueOf(device.getId()) + userId + String.valueOf(System.currentTimeMillis());
        command.setId(Long.parseLong(commandId));
        if(!DeviceConstant.STATUS_ONLINE.equals(device.getStatus())){
            command.setCode(500);
            command.setMessage("设备不在线");
            insertCommand(command);
            return;
        }
        Map<String,Object> paramsMap = null;
        try{
            paramsMap = JSON.parseObject(params,new TypeReference<Map<String, Object>>(){});
        }catch (Exception e){
            log.error("指令参数格式错误",e);
            command.setCode(500);
            command.setMessage("指令参数格式错误:"+e.getMessage());
            insertCommand(command);
            return;
        }
        try{
            //发送设备指令,发送到不同的网关
            CommandPostMessage commandPostMessage = new CommandPostMessage();
            commandPostMessage.setId(command.getId());
            commandPostMessage.setChannelKey(channelKey);
            commandPostMessage.setProductKey(productKey);
            commandPostMessage.setDeviceKey(deviceKey);
            commandPostMessage.setTime(new Date());
            commandPostMessage.setParams(paramsMap);
            // 同步发送
            rocketMQTemplate.syncSend(RocketTopicConstant.COMMAND_POST+product.getTransformService(),commandPostMessage);
            command.setCode(200);
            command.setMessage("发送成功");
            insertCommand(command);
        }catch (Exception e){
            command.setCode(500);
            command.setMessage("发送失败：:"+e.getMessage());
            insertCommand(command);
        }
    }
}
